package src.main.java.com.pms.service;

import src.main.java.com.pms.util.InputUtil;
import src.main.java.com.pms.util.JDBCUtil;

import java.sql.ResultSet;
import java.sql.SQLException;

public class PetBasicService {

    /**
     * 添加宠物
     */
    public void addPet() {
        String name = InputUtil.getString("输入宠物名: ");
        if (name.trim().isEmpty()) {
            System.out.println("名字不能为空，请重新输入。");
            return;
        }

        String type = InputUtil.getString("输入宠物类型: ");
        if (type.trim().isEmpty()) {
            System.out.println("类型不能为空，请重新输入。");
            return;
        }

        int age = InputUtil.getInt("输入宠物年龄: ");
        if (age < 0) {
            System.out.println("年龄不能小于0，请重新输入。");
            return;
        }

        String sql = "INSERT INTO Pets (name, type, age) VALUES (?, ?, ?)";
        try {
            int result = JDBCUtil.executeUpdateWithParams(sql, name, type, age);
            if (result > 0) {
                System.out.println("宠物添加成功！");
            } else {
                System.out.println("宠物添加失败");
            }
        } catch (SQLException | ClassNotFoundException e) {
            System.out.println("添加宠物时发生错误: " + e.getMessage());
        }
    }

    /**
     * 查看所有宠物
     */
    public void viewPets() {
        String sql = "SELECT * FROM Pets WHERE deleted = 0";
        try (ResultSet rs = JDBCUtil.executeQueryWithConnection(sql)) {
            while (rs.next()) {
                printPetInfo(rs);
            }
        } catch (SQLException | ClassNotFoundException e) {
            System.out.println("查看宠物信息时发生错误: " + e.getMessage());
        }
    }

    /**
     * 更新宠物信息
     */
    public void updatePet() throws SQLException, ClassNotFoundException {
        int id = InputUtil.getInt("请输入要更新的宠物ID: ");
        if (id <= 0) {
            System.out.println("ID不能小于等于0");
            return;
        }

        // 检查宠物是否存在
        if (!isPetExists(id)) {
            System.out.println("未找到该宠物");
            return;
        }

        String name = InputUtil.getString("请输入新的宠物名称（直接回车保持不变）: ");
        String type = InputUtil.getString("请输入新的宠物类型（直接���车保持不变）: ");
        int age = InputUtil.getInt("请输入新的宠物年龄（输入-1保持不变）: ");

        StringBuilder sql = new StringBuilder("UPDATE Pets SET ");
        boolean needUpdate = false;

        if (!name.trim().isEmpty()) {
            sql.append("name = ?, ");
            needUpdate = true;
        }
        if (!type.trim().isEmpty()) {
            sql.append("type = ?, ");
            needUpdate = true;
        }
        if (age >= 0) {
            sql.append("age = ?, ");
            needUpdate = true;
        }

        if (!needUpdate) {
            System.out.println("没有需要更新的信息");
            return;
        }

        sql.setLength(sql.length() - 2); // 删除最后的逗号和空格
        sql.append(" WHERE id = ? AND deleted = 0");

        try {
            int result = JDBCUtil.executeUpdateWithParams(sql.toString(), name, type, age, id);
            if (result > 0) {
                System.out.println("宠物信息更新成功！");
            } else {
                System.out.println("宠物信息更新失败");
            }
        } catch (SQLException | ClassNotFoundException e) {
            System.out.println("更新宠物信息时发生错误: " + e.getMessage());
        }
    }

    /**
     * 删除宠物（逻辑删除）
     */
    public void deletePet() {
        int id = InputUtil.getInt("输入要删除的宠物ID: ");
        if (id <= 0) {
            System.out.println("ID不能小于等于0");
            return;
        }

        String sql = "UPDATE Pets SET deleted = 1 WHERE id = ? AND deleted = 0";
        try {
            int result = JDBCUtil.executeUpdateWithParams(sql, id);
            if (result > 0) {
                System.out.println("宠物删除成功！");
            } else {
                System.out.println("宠物删除失败，可能该宠物不存在或已被删除");
            }
        } catch (SQLException | ClassNotFoundException e) {
            System.out.println("删除宠物时发生错误: " + e.getMessage());
        }
    }

    /**
     * 按名字搜索宠物
     */
    public void searchPetByName() {
        String name = InputUtil.getString("输入要搜索的宠物名字: ");
        if (name.trim().isEmpty()) {
            System.out.println("搜索名字不能为空");
            return;
        }

        String sql = "SELECT * FROM Pets WHERE name LIKE ? AND deleted = 0";
        try (ResultSet rs = JDBCUtil.executeQueryWithConnection(sql, "%" + name + "%")) {
            boolean found = false;
            while (rs.next()) {
                found = true;
                printPetInfo(rs);
            }
            if (!found) {
                System.out.println("未找到符合条件的宠物");
            }
        } catch (SQLException | ClassNotFoundException e) {
            System.out.println("搜索宠物时发生错误: " + e.getMessage());
        }
    }

    /**
     * 打印宠物信息
     */
    private void printPetInfo(ResultSet rs) throws SQLException {
        System.out.println("ID: " + rs.getInt("id") +
                ", 名字: " + rs.getString("name") +
                ", 类型: " + rs.getString("type") +
                ", 年龄: " + rs.getInt("age") +
                ", 创建时间: " + rs.getTimestamp("created_at") +
                ", 更新时间: " + rs.getTimestamp("updated_at"));
    }


//    /**
//     * 检查宠物是否存在
//     * @param id
//     * @return
//     */
//    private boolean isPetExists(int id) {
//        String sql = "SELECT COUNT() FROM Pets WHERE id = ? AND deleted = 0";
//        try (ResultSet rs = JDBCUtil.executeQueryWithConnection(sql, id)) {
//            if (rs.next()) {
//                return rs.getInt(1) > 0;
//            }
//            return false;
//        } catch (SQLException | ClassNotFoundException e) {
//            System.out.println("检查宠物是否存在时发生错误: " + e.getMessage());
//            return false;
//        }
//    }

    /**
     * 添加宠物（GUI版本）
     * @param name 宠物名称
     * @param type 宠物类型
     * @param age 宠物年龄
     * @return 是否添加成功
     */
    public boolean addPet(String name, String type, int age) throws SQLException, ClassNotFoundException {
        if (name.trim().isEmpty() || type.trim().isEmpty() || age < 0) {
            return false;
        }

        String sql = "INSERT INTO Pets (name, type, age) VALUES (?, ?, ?)";
        int result = JDBCUtil.executeUpdateWithParams(sql, name, type, age);
        return result > 0;
    }

    /**
     * 获取所有未删除的宠物
     * @return ResultSet 包含所有宠物信息
     */
    public ResultSet getAllPets() throws SQLException, ClassNotFoundException {
        String sql = "SELECT * FROM Pets WHERE deleted = 0";
        return JDBCUtil.executeQueryWithConnection(sql);
    }

    /**
     * 根据ID获取宠物信息
     * @param id 宠物ID
     * @return ResultSet 包含宠物信息
     */
    public ResultSet getPetById(int id) throws SQLException, ClassNotFoundException {
        String sql = "SELECT * FROM Pets WHERE id = ? AND deleted = 0";
        return JDBCUtil.executeQueryWithConnection(sql, id);
    }

    /**
     * 更新宠物信息（GUI版本）
     * @param id 宠物ID
     * @param name 新的宠物名称
     * @param type 新的宠物类型
     * @param age 新的宠物年龄
     * @return 是否更新成功
     */
    public boolean updatePet(int id, String name, String type, int age) throws SQLException, ClassNotFoundException {
        if (name.trim().isEmpty() || type.trim().isEmpty() || age < 0) {
            return false;
        }

        String sql = "UPDATE Pets SET name = ?, type = ?, age = ? WHERE id = ? AND deleted = 0";
        int result = JDBCUtil.executeUpdateWithParams(sql, name, type, age, id);
        return result > 0;
    }

    /**
     * 删除宠物（GUI版本）
     * @param id 宠物ID
     * @return 是否删除成功
     */
    public boolean deletePet(int id) throws SQLException, ClassNotFoundException {
        String sql = "UPDATE Pets SET deleted = 1 WHERE id = ? AND deleted = 0";
        int result = JDBCUtil.executeUpdateWithParams(sql, id);
        return result > 0;
    }

    /**
     * 按名字搜索宠物（GUI版本）
     * @param name 搜索的宠物名字
     * @return ResultSet 包含搜索结果
     */
    public ResultSet searchPetsByName(String name) throws SQLException, ClassNotFoundException {
        String sql = "SELECT * FROM Pets WHERE name LIKE ? AND deleted = 0";
        return JDBCUtil.executeQueryWithConnection(sql, "%" + name + "%");
    }

    /**
     * 检查宠物是否存在（GUI版本）
     * @param id 宠物ID
     * @return 是否存在
     */
    public boolean isPetExists(int id) throws SQLException, ClassNotFoundException {
        String sql = "SELECT COUNT(*) FROM Pets WHERE id = ? AND deleted = 0";
        ResultSet rs = JDBCUtil.executeQueryWithConnection(sql, id);
        if (rs.next()) {
            return rs.getInt(1) > 0;
        }
        return false;
    }
}

